//
//  EmoticonController.swift
//  表情键盘
//
//  Created by lujun on 2021/11/24.
//

import UIKit
private let kCellId: String = "kCellId"
class EmoticonController: UIViewController {
    var emoticonCallBack: ( _ emoticon: Emoticon) -> ()
    private lazy var manager = EmoticonManager()
    
  private lazy var collectionView1: UICollectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: EmoticonCollectionViewLayout())
  private lazy var toolBar1: UIToolbar = UIToolbar()
    
    init(emoticonCallBack: @escaping( _ emoticon: Emoticon) -> ()){
        self.emoticonCallBack = emoticonCallBack
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
   override func viewDidLoad() {
        super.viewDidLoad()
       setupUI()
     }
}
extension EmoticonController{
    private func setupUI(){
        view.addSubview(collectionView1)
        view.addSubview(toolBar1)
//        collectionView1.backgroundColor = UIColor.randomColor()
        toolBar1.backgroundColor = UIColor.randomColor()
        toolBar1.frame = CGRect(x: 0, y: 0, width: kScreenW, height: 44)
        collectionView1.frame = CGRect(x: 0, y: 0, width: kScreenW, height: 200)
        collectionView1.translatesAutoresizingMaskIntoConstraints = false
        toolBar1.translatesAutoresizingMaskIntoConstraints = false
        let views = ["tBar": toolBar1,"cView": collectionView1]
        var cons = NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[tBar]-0-|", options: [], metrics: nil, views: views)
        cons += NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[cView]-0-[tBar]-0-|", options: [.alignAllLeft,.alignAllRight], metrics: nil, views: views)
        view.addConstraints(cons)
        prepareForCollectionView()
        prepareForToolBar()
    }
    private func prepareForCollectionView(){
        collectionView1.register(EmoticonViewCell.self, forCellWithReuseIdentifier: kCellId)
        collectionView1.dataSource = self
        collectionView1.delegate = self
        
    }
    private func prepareForToolBar(){
        var index: Int = 0
        let titles = ["最近","默认","emoji","浪小花"]
        var items = [UIBarButtonItem]()
        for title in titles {
            let item = UIBarButtonItem(title: title, style: .plain, target: self, action: #selector(itemClick(item:)) )
            item.tag = index
            index += 1
            
            items.append(item)
            items.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil))
            
        }

        items.removeLast()
        toolBar1.items = items
        
        toolBar1.tintColor = UIColor.orange
    }
    @objc func itemClick(item: UIBarButtonItem){
        let tag = item.tag
        let indexPath = NSIndexPath(item: 0, section: tag)
        collectionView1.scrollToItem(at: indexPath as IndexPath, at: .left, animated: true)
        
        
    }
    
}
extension EmoticonController : UICollectionViewDataSource{
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return manager.packages.count
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        let package = manager.packages[section]
        
        
        return package.emoticons.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kCellId, for: indexPath) as! EmoticonViewCell
        let pachage = manager.packages[indexPath.section]
        let em = pachage.emoticons[indexPath.item]
        
        
//       cell.backgroundColor = indexPath.item % 2 == 0 ? UIColor.red : UIColor.blue
        cell.emoticon = em
        return cell
    }
    
}

extension EmoticonController: UICollectionViewDelegate{
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
//        debugPrint("aaa\(indexPath.item)")
        let package = manager.packages[indexPath.section]
        let emoticon = package.emoticons[indexPath.item]
        self.insertIntoRecentlyEmoticon(emoticon: emoticon)
        emoticonCallBack(emoticon)
    }
    private func insertIntoRecentlyEmoticon(emoticon: Emoticon){
        if emoticon.isRemove || emoticon.isEmpty {
            return
        }
        if manager.packages.first!.emoticons.contains(emoticon) {
//            let index1 = (manager.packages.first?.emoticons.index(of: emoticon))!
            let index = ( manager.packages.first?.emoticons.firstIndex(of: emoticon))!
            manager.packages.first?.emoticons.remove(at: index)
        }else{
            manager.packages.first?.emoticons.remove(at: 19)
        }
        manager.packages.first?.emoticons.insert(emoticon, at: 0)
    }
}

class EmoticonCollectionViewLayout: UICollectionViewFlowLayout {
    override func prepare() {
        super.prepare()
        let itemWH = kScreenW / 7
        itemSize = CGSize(width: itemWH, height: itemWH)
        minimumLineSpacing = 0
        minimumInteritemSpacing = 0
        scrollDirection = .horizontal
        
        collectionView?.isPagingEnabled = true
        collectionView?.showsVerticalScrollIndicator = false
        collectionView?.showsHorizontalScrollIndicator = false
        let insertMargin = ( collectionView!.bounds.height - 3 * itemWH ) / 2
        collectionView?.contentInset = UIEdgeInsets(top: insertMargin, left: 0, bottom: insertMargin, right: 0)
    }
}
